package com.cgtong.android.util;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.net.Uri;
import android.support.v4.app.FragmentActivity;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.content.DialogInterface;
import android.view.KeyEvent;
import android.provider.Settings.Secure;  
import android.telephony.TelephonyManager;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.cgtong.android.R;
import com.cgtong.android.bean.VersionBean;
import com.cgtong.android.http.ApiManager;
import com.cgtong.android.http.ConstantManager;
import com.cgtong.android.widget.BaseDialog;
import com.google.gson.Gson;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.CallBack;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;

import org.litepal.util.Const;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Tinwai on 2017/10/25.
 */

public class CommonUtils {
    /**
     * 显示用户头像（本地）
     */
    public static void setUserAvatar(Context context, ImageView imageView, int avatarId) {
        TypedArray avatars = context.getResources().obtainTypedArray(R.array.avatars);
        imageView.setImageResource(avatars.getResourceId(avatarId > 0 ? (avatarId - 1) : 0, 0));
    }

    /**
     * 版本更新
     */
    public static void getversion() {
        getversion(null);
    }

    /**
     * 版本更新
     */
    public static void getversion(final CallBack<Integer> callBack) {
        EasyHttp.post(ApiManager.URL_GET_VERSIONS)
                .params("version_mark", "10000")
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {
                        ToastUtils.showShort(e.getMessage());
                        if (null != callBack) {
                            callBack.onError(e);
                        }
                    }

                    @Override
                    public void onSuccess(String s) {
                        VersionBean versionBean = new Gson().fromJson(s, VersionBean.class);
                        if (versionBean.getCode() == 0) {
                            VersionBean.Version version = versionBean.getData();
                            if (null != callBack) {
                                callBack.onSuccess(ConstantManager.VERSION_UPDATE_UI);
                            }
                            parseVersion(version, callBack);
                        } else {
                            if (null != callBack) {
                                callBack.onCompleted();
                            }
                        }
                    }
                });
    }

    private static void parseVersion(VersionBean.Version version, final CallBack<Integer> callBack) {
        if (version != null) {
            String versionStr = version.getVersion();
            int versionCode = Integer.parseInt(versionStr);//最新版本号
            final String versionName = version.getVersionName();//最新版本名
            final String versionFile = version.getDownloadUrl();//最新版本更新地址
            final String content = version.getDescription();//最新版本更新内容
            final int updateModel = Integer.parseInt(version.getForceIsUpdate());//更新机制：1：强制更新 0：可选择更新

            int appVersionCode = AppUtils.getAppVersionCode();
            LogUtils.d("appVersionCode : " + appVersionCode);
            if (versionCode > appVersionCode) {
                //------------弹出框开始--------------
                BaseDialog.create(((FragmentActivity) ActivityUtils.getTopActivity()).getSupportFragmentManager())
                        .setLayoutRes(R.layout.dialog_normal_layout)
                        .setViewListener(new BaseDialog.ViewListener() {      // 可以进行一些必要对View的操作
                            @Override
                            public void bindView(final View view, final Dialog dialog) {
                                TextView titleTxt = (TextView) view.findViewById(R.id.title);
                                TextView messageTxt = (TextView) view
                                        .findViewById(R.id.message);
                                Button okBtn = (Button) view
                                        .findViewById(R.id.positiveButton);
                                Button cancelBtn = (Button) view
                                        .findViewById(R.id.negativeButton);
                                okBtn.setText("确定");
                                //-------------
                                if(null != callBack && null != dialog){
                                    dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                                        @Override
                                        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                                            if (keyCode == KeyEvent.KEYCODE_BACK) {
                                                return true;
                                            }
                                            return false;
                                        }
                                    });
                                }
                                //显示内容
                                StringBuffer sb = new StringBuffer();
                                if (updateModel == 1) {//强制更新
                                    titleTxt.setText("强制更新");
                                    sb.append("版本:" + versionName);
                                    sb.append("\n" + content);
                                    cancelBtn.setText("退出");
                                    cancelBtn.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            dialog.dismiss();
                                            if (null != callBack) {
                                                callBack.onSuccess(ConstantManager.VERSION_UPDATE_EXIT);
                                            }
                                            //退出程序
                                            ActivityUtils.getTopActivity().finish();
                                        }
                                    });
                                    okBtn.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            dialog.dismiss();
                                            doDownloadByBrowser(versionFile);
                                            if (null != callBack) {
                                                callBack.onSuccess(ConstantManager.VERSION_UPDATE_ENFORCE);
                                            }
                                            ActivityUtils.getTopActivity().finish();
                                        }
                                    });
                                } else {//选择更新
                                    titleTxt.setText("版本更新");
                                    sb.append("版本:" + versionName);
                                    sb.append("\n" + content);
                                    cancelBtn.setText("忽略");
                                    cancelBtn.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            dialog.dismiss();
                                            if (null != callBack) {
                                                callBack.onSuccess(ConstantManager.VERSION_UPDATE_INGORE);
                                            }
                                        }
                                    });
                                    okBtn.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            dialog.dismiss();
                                            if (null != callBack) {
                                                callBack.onSuccess(ConstantManager.VERSION_UPDATE_NORMAL);
                                            }
                                            doDownloadByBrowser(versionFile);
                                        }
                                    });
                                }
                                messageTxt.setText(sb.toString());

                            }
                        })
                        .setDimAmount(0.2f)
                        .setCancelOutSide(false)
                        .setGravity(Gravity.CENTER)
                        .setStyle(R.style.CenterDialogTheme)
                        .show();
            } else {
                if (null != callBack) {
                    callBack.onCompleted();
                }
                ToastUtils.showShort("当前已是最新版本");
            }
            //------------弹出框结束--------------
        } else {
            if (null != callBack) {
                callBack.onCompleted();
            }
            ToastUtils.showShort("当前已是最新版本");
        }
    }

    private static void doDownloadByBrowser(String url) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        Uri uri = Uri.parse(url);
        intent.setData(uri);
        ActivityUtils.getTopActivity().startActivity(Intent.createChooser(intent, "请选择浏览器"));
    }

    /**
     * 检测密码匹配规则
     *
     * @param password
     * @return true 代表匹配密码规则 false 代表不匹配密码规则
     */
    public static boolean checkPasswordRule(String password) {
        /*Pattern pAll = Pattern.compile("^((?=[\\x21-\\x7e]*\\d+[\\x21-\\x7e]*[a-zA-Z]+).{6,})|((?=[\\x21-\\x7e]*[a-zA-Z]+[\\x21-\\x7e]*\\d+).{6,})$");
        Matcher mAll = pAll.matcher(password);
        return mAll.find();*/
        return password.length() >= 6;
    }

    /**
     * 获取设备信息
     */
    public static String getMobileInfo(Context context){
        StringBuffer mobileInfoStr = new StringBuffer();
        DeviceUuidFactory deviceuuidFactory = new DeviceUuidFactory(context);
        mobileInfoStr.append(android.os.Build.BRAND+","); //品牌机型
        mobileInfoStr.append(android.os.Build.MODEL+","); //型号
        mobileInfoStr.append(android.os.Build.VERSION.RELEASE+","); //版本
        mobileInfoStr.append(deviceuuidFactory.getDeviceUuid()); //唯一标识
        //android.util.Log.i("bbbb","mobileInfoStr:"+mobileInfoStr.toString());
        return mobileInfoStr.toString();
    }

    /**
     * 检测是否有emoji表情
     *
     * @param source
     * @return
     */
    public static boolean containsEmoji(String source) {
        int len = source.length();
        for (int i = 0; i < len; i++) {
            char codePoint = source.charAt(i);
            if (!isEmojiCharacter(codePoint)) {  //如果不能匹配,则该字符是Emoji表情
                return true;
            }
        }
        return false;
    }

    /**
     * 判断是否是Emoji
     *
     * @param codePoint   比较的单个字符
     * @return
     */
    private static boolean isEmojiCharacter(char codePoint) {
        return (codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA) || (codePoint == 0xD)
                || ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) || ((codePoint >= 0xE000) && (codePoint <= 0xFFFD))
                || ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF));
    }
}